package com.cat.dynamicPlanning;

import java.util.Arrays;

/**
 *   @description https://leetcode.cn/problems/maximum-number-of-operations-with-the-same-score-ii/description/
 *   @author 曲大人的喵
 *   @create 2025/9/6 18:55
 *   @since JDK17
 */

public class Solution90 {
    int f(int[] nums, int target) {
        int n = nums.length;
        int[][] dp = new int[n][n];
        for (int i = 0; i < n - 1; i++) {
            dp[i][i + 1] = nums[i] + nums[i + 1] == target ? 1 : 0;
        }
        for (int l = n - 3; l >= 0; l--) {
            for (int r = l + 2; r < n; r++) {
                int ans = 0;
                if (nums[l] + nums[r] == target) {
                    ans = 1 + dp[l + 1][r - 1];
                }
                if (nums[l] + nums[l + 1] == target) {
                    ans = Math.max(ans, 1 + dp[l + 2][r]);
                }
                if (nums[r] + nums[r - 1] == target) {
                    ans = Math.max(ans, 1 + dp[l][r - 2]);
                }
                dp[l][r] = ans;
            }
        }
        return dp[0][n - 1];
    }
    public int maxOperations(int[] nums) {
        int ans = 0, n = nums.length;
        if (n == 2) {
            return 1;
        }
        ans = f(Arrays.copyOfRange(nums, 2, n), nums[0] + nums[1]);
        ans = Math.max(ans, f(Arrays.copyOfRange(nums, 1, n - 1), nums[0] + nums[n - 1]));
        ans = Math.max(ans, f(Arrays.copyOfRange(nums, 0, n - 2), nums[n - 1] + nums[n - 2]));
        return ans + 1;
    }
}
